from datetime import datetime
import random


from flask import Blueprint, jsonify, request,json
from views.goods import g_blue
from db import db # 导入数据库
from utils.myredis import r

index_blue=Blueprint('index_blue',__name__)


# 获取商家信息进行缓存
# 配置路由
@index_blue.route('/getshops')
def getshops():
    # 读取缓存，如果有直接转换成json字符串进行返回，没有查询数据库
    code='001'
    key="shop"+code   # 为了更好的分清楚id
    # r调用是调用sql数据库中的数据,获取缓存中的数据
    # 先取出
    shop=r.get_str(key)
    if not shop:
        # 并发访问的时候，只能一个人访问  ?????????????????
        res=r.setnx_str(key+'exit',key+'exit')
        if res:
            # 查询数据库中的所有数据  where 后是条件精准查询 第一
            sql = "select * from shops where code='001'"
            # shop 为结果
            shop = db.find(sql)
            # 把数据库中的数据放在这里进行缓存
            r.set_str(key,json.dumps(shop))
    else:
        # 否则将数据库中的数据转换为json字符串
        shop=json.loads(shop)
    return jsonify({'code':200,'shops':shop})

# 获取所有分类接口
@index_blue.route("/getcates") # 默认采用get方法
def getcates():
    # 获取数据库中的cates字段
    # r.remove_str("cates")
    cates=r.get_str("cates")
    if not cates:
        sql="select id,name from category order by sort asc"
        res=db.find_all(sql) #获取排序后所有的数据
        data = [{'id': str(i['id']), 'text': i['name']} for i in res]
        r.set_str('cates',json.dumps(data))
    else:
        res=json.loads(cates)
    return jsonify({
        'code':200,
        "catelist":res
    })



# 根据id获取分类下的所有数据
@index_blue.route("/idgetcates") # 默认采用get方法
def idgetcates():
    # 获取数据库中的cates字段
    cateid=request.args.get("cateid") # 获取分类的id
    # r.remove_str("goods" + cateid)
    goods=r.get_str('goods'+cateid) # 获取缓存中此分类下的商品
    if not goods:
        sql="select id,name,image,price,description from dish where category_id=%d and is_deleted=0"%(int(cateid))
        res=db.find_all(sql) #获取排序后所有的数据
        # 根据菜品id查询对应的菜品
        data=[]
        for i in res:
            dict = {'id': str(i['id']), 'name': i['name'], 'price': float(i['price']), 'image': i['image'],'description': i['description']}
            sql1="select value from dish_flavor where dish_id=%d"%(int(i['id']))
            flavors=db.find_all(sql1)
            flist=[]
            for j in flavors:
                flist.append(json.loads(j['value']))
            dict['flavors']=flist
            data.append(dict)
        # 加入缓存
        r.set_str('goods'+cateid,json.dumps(data))
    else:
        data=json.loads(goods)
    return jsonify({
        'code':200,
        "catelist":data
    })


# 添加到购物车接口
@index_blue.route('/addcart')
def addcart():
    # 获取参数userid gid count ['少糖','少盐']  type(1菜品 2套餐)
    userid=request.args.get('userid')
    gid=request.args.get('gid')
    count=request.args.get('count')
    type=request.args.get('type')
    flavors=request.args.get('flavors')


    r.del_hash('cart' + str(userid) + 'goods' + str(gid))

    # 查询某个商品是否存在
    pkey='cart'+str(userid)+'goods'+str(gid)

    flag=r.is_exits(pkey)
    if int(flag)==0 :
        # 不存在添加
        r.hash_add(pkey,gid,count)
        r.hash_add(pkey,'type',type)
        r.hash_add(pkey,'flavors',json.dumps(flavors))
        # 把商品名称和价格以名字和price存入

    else:
        # 存在数量更新
        r.hash_hincrby(pkey,gid,count,type)
    # 返回结果
    return jsonify( {
        'code':200,
        'msg':'购买成功'
    })
# ---------------------------------------------------------------8/30号了解透彻

# 我的购物车数据封装
def getcardata(userid):
    # 根据userid模糊查询购物车信息
    carts=r.findall_str('cart'+str(userid))
    # 遍历购物车，查每一个商品的属性
    clist=[]
    tcount=0
    for i in carts:
        dict={}
        goods=r.hash_getall(i.decode())
        for k,v in goods.items():
            kk=k.decode()
            vv=v.decode()
            if kk=='type':
                dict['type']=vv
            elif kk=='flavors':
                dict['flavors']=json.loads(vv)
            else:
                dict['id']=kk
                dict['count']=vv
                tcount+=int(vv)
        clist.append(dict)
    tmoney=0
    if len(clist)>0:
        for i in clist:
         # 根据id和类型查询名称和价格 1单品2套餐
            if i['type'] ==1:
                sql="select name,price,description,image  from dish where id=%d"%(int(i['id']))

            else:
                sql="select name,price,description,image  from dish where id=%d"%(int(i['id']))
            res=db.find(sql)
            # 重组
            i['name']=res['name']
            i['price']=float(res['price'])
            i['description']=res['description']
            i['image']=res['image']
            tmoney+=i['price']
    return clist, tmoney, tcount


# 根据userid获取获取购物车的相关数据
@index_blue.route('/mycart')
def mycart():
    # 获取userid
    userid=request.args.get('userid')
    #根据userid模糊查询购物车的信息
    carts=r.findall_str('cart'+str(userid))
    # r.remove_str('cart'+str(userid))
    # 遍历购物车车，查每一个商品的属性
    clist=[]
    tcount=0
    for i in carts:
        dict={}
        goods=r.hash_getall(i.decode())
        for k,v in goods.items():
            kk=k.decode()
            vv=v.decode()
            if kk=='type':
                dict['type']=vv
            elif kk=='flavors':
                dict['flavors']=json.loads(vv)
            else:
                dict['id']=kk
                dict['count']=vv
                tcount+=int(vv)
        clist.append(dict)
    tmoney=0
    if len(clist)>0:
        for i in clist:
         # 根据id和类型查询名称和价格 1单品2套餐
            if i['type'] ==1:
                sql="select name,price,description  from dish where id=%d"%(int(i['id']))

            else:
                sql="select name,price,description  from dish where id=%d"%(int(i['id']))
            res=db.find(sql)
            # 重组
            i['name']=res['name']
            i['price']=float(res['price'])
            i['description']=res['description']
            tmoney+=i['price']
        # 返回结果
        return jsonify({
                'code':200,
                'clist':clist,
                'tmoney':tmoney,
                'tcount':tcount,
            })

# 购物车的根据id获取口味的值
@index_blue.route('/test')
def test():
    list1=[{
        'id':1,
        'name':'iq手机',
        'pid':0,
    },{
        'id':2,
        'name':'华为手机',
        'pid':1,
    },{
        'id':3,
        'name':'小米手机/红米',
        'pid':2
    },{
        'id':4,
        'name':'vivo手机',
        'pid':3
    },{
        'id':5,
        'name':'OPPO手机',
        'pid':4
    }]
    dict={}
    for i in list1:
        dict[i['id']]=i
    reslist=[]
    for j in list1:
        pid=j['pid']
        if pid==0:
            reslist.append(j)
        else:
            if 'son' not in dict[pid]:
                dict[pid]['son']=[]
            dict[pid]['son'].append(j)
    return jsonify({"ist":reslist})


# 无限极分类
def xhtme(data):
    list1=[]
    # 判断传的值的长度是否小于等于0 返回一个空列表
    if len(data)<=0:
        return list1
    dict={}
    # 如果传的值的长度大于0 则for 循环传入
    for i in data:
        # 如果 dict
        dict[i['code']]=i
    list=[]
    for j in data:
        pid=j['pid']
        if pid==None:
            list.append(j)
        else:
            if 'son' not in dict[pid]:
                dict[pid]['son']=[]
            dict[pid]['son'].append(j)
    return list


@index_blue.route('/citylist')
def citylist():
    citylist=r.get_str('citylist')
    if not citylist:
        # 查询数据库中的所有数据
        sql="select * from tb_areas"
        res=db.find_all(sql)
        list=xhtme(res)
        r.set_str('citylist',json.dumps(list))
    else:
        list=json.loads(citylist)
    return jsonify({'code':200,'list':list})

@index_blue.route("/jiajia")
def jiajia():
    # 获取userid gid count type
    userid=request.args.get('userid')
    gid=request.args.get('gid')
    count=request.args.get('count')
    type=request.args.get('type')
    # 查询购物车中此商品是否存在
    key="cart"+str(userid)+'goods'+str(gid)
    if r.is_exits(key):
        tcount=count
        #1加 2减
        if type==2:
            tcount="-"+str(count)
        res=r.hash_hincrby(key,gid,tcount,type)
        # 判断结果
        if res =='false':
            return jsonify({
                'code':10011,
                'mes':'减的数量必须小于当前购买数量'
            })
        else:
            return jsonify({'code':200})
    else:
        return jsonify({'code':10010,'mes':'没买过此商品'})


# 添加订单页面
@index_blue.route('/add_orders',methods=['POST'])
def add_orders():
    print('订单')

    # 获取订单表的数据

    data=json.loads(request.data)
    userid=data['userid']
    address_id=data['address_id']
    message=data['message']
    paytype=data['paytype']
    # redis hash获取购物车
    clist,tmoney,tcount=getcardata(userid)
    # 根据购物车查价格图片
    if len(clist) > 0:
        # 事务的处理
        # 创建时间
        now = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
        # 订单号 年月日+userid+5位随机数
        code = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S') + str(userid) + str(random.randint(10000, 99999))
        # 写入订单表

        try:
            sql = "insert into orders(number,status,user_id,address_book_id,order_time,pay_method,amount,remark,phone,address,user_name,consignee,checkout_time) values('%s',%d,%d,%d,'%s',%d,'%s','%s','%s','%s','%s','%s','%s')" % (
            code, 1, int(userid), int(address_id), now, int(paytype), tmoney, message, '1', '1', '1', '1',
            '2020-10-10 10:10:10')
            db.update(sql)

            # 写入详情表
            for i in clist:
                if int(i['type']) == 1:
                    dish_id = i['id']
                    setmeal_id = 0
                else:
                    dish_id = 0
                    setmeal_id = i['id']
                sql1 = "insert into order_detail(name,image,order_id,dish_id,setmeal_id,dish_flavor,number,amount) values('%s','%s','%s',%d,%d,'%s',%d,'%s')" % (
                i['name'], i['image'], code, int(dish_id), int(setmeal_id), json.dumps(i['flavors']), int(i['count']),
                float(i['price']))
                db.update(sql1)
            db.commit()

            # 清空购物车 通过key
            r.removeall_str('cart' + str(userid))
            return jsonify({'code': 200})
        except:
            # 回滚购物车
            db.rollback()
            return jsonify({
                'code': 20010
            })
    else:
        return jsonify({
            'code':20011,
            'msg':'没有可以生成的订单'
        })









# 添加收货地址
@index_blue.route('/add',methods=['GET','POST','PUT'])
def add():
    if request.method=='POST':
        userid = 211
        data = json.loads(request.data)
        is_default = 0

        if data['isDefault']:
            is_default = 1
        create_time = datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
        update_time = datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
        sql = "insert into address_book(user_id,consignee,phone,province_code,province_name,city_code,city_name,district_code,district_name,detail,is_default,create_time,update_time,create_user,update_user)" \
              "values (%d,'%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,'%s','%s',%d,%d)"%(int(userid),data['name'],data['tel'],data['postalCode'],data['province'],data['areaCode'],data['city'],data['country'],data['county'],data['addressDetail'],is_default,create_time,update_time,userid,userid)
        db.update(sql)
        db.commit()
        return jsonify({
            "code":200,
            "msg":'添加成功'
        })
    elif request.method == 'GET':
        userid = request.args.get('userid')
        list = r.get_str('add' + str(userid))
        if not list:
            sql = "select consignee,phone,province_name,city_name,district_name,detail,is_default from address_book where userid=%d" % int(
                userid)
            res = db.find(sql)
            r.set_str('add' + str(userid), json.dumps(res))
        else:
            res = json.loads(list)

        return jsonify({
            "code": 200,
            "msg": '地址',
            'addlist': res
        })
    else:
        userid = request.args.get('userid')
        try:
            sql1 = "update address_book set is_default=0 where user_id=%d and is_default=1" % int(userid)
            db.update(sql1)
            db.commit()
            sql2 = "update address_book set is_default=1 where id=%d" % int(userid)
            db.update(sql2)
            db.commit()
        except Exception as e:
            print(e)

        return jsonify({
            "code": 200,
            'msg': '修改成功'
        })

